import MenuIndex from "@/components/MenuIndex";
import TableV2, { TableV2Type } from "@/components/TableV2";
import { WorkArea } from "@/components/WorkArea";
import { onEnterKeydown } from "@/hoc/onEnterDown";
import { ConditionItemType, ToolsItemType } from "@/hooks/useElementFormItem";
import { useEnable } from "@/hooks/useEnable";
import { useTableV2 } from "@/hooks/useTableV2";
import apiStore from "@/stores/apiStore";
import { httpCommonHandle } from "@/utils/httpUtils";
import { AddCommdity, CommodityListType, CommonOption, EditCommdity, serviceConfig } from "@Tea/model";
import { changeDataMutual, isSuccessCode, useElMessageBox } from "@Tea/utils";
import { defineComponent, onMounted, reactive, ref } from "vue";
import TeaDialog, { TeaTitleType } from "./modules/TeaDialog";
import { ElImage } from "element-plus"
import TeaItemDialog from "./modules/TeaItemDialog";

const CommodityManage = defineComponent({
  setup() {
    const tableName = 'CommodityManage'
    const baseUrl = `http://127.0.0.1:${serviceConfig.port}/`
    const { tableLoading, mountSearch,resetCurPage ,handleRadioRow,assginPaging,commonSearch} = useTableV2(tableName)
    const { getTypeList, getTeaList, enableCommdity } = apiStore().api
    
    // 搜索条件
    const searchForm = reactive({
      enable: 1 as 0 | 1,
      teaType: "" as "",
      teaName: "",
    })

    // 新增\编辑弹框
    const visible = ref(false)
    const title = ref<TeaTitleType>('新增茶叶')
    const ruleForm: AddCommdity | EditCommdity = reactive({
      teaId: "",
      cover: "",
      price: "",
      number: "",
      teaName: "",
      teaType:""
    })

    // 更多详情弹框
    const teaDetailVisible = ref(false)
    const targetTeaId = ref('' as CommodityListType['teaId'] | '')

    // 茶叶类型
    const teaTypeOptions = ref<CommonOption[]>([])

    const { handleEnable, buttonFlag, checkboxFlag } = useEnable({ tableName, origin: searchForm })

    // 添加商品
    const add = () => {
      // 删除taeId
      delete (ruleForm as EditCommdity).teaId
      title.value = "新增茶叶"
      visible.value = true
    }

    // 编辑商品
    const edit = () => {
      handleRadioRow<CommodityListType>((data) => {
        (ruleForm as EditCommdity).teaId = 0
        changeDataMutual(ruleForm, data)
        title.value = "编辑茶叶"
        visible.value = true
      })
    }

    // 查询数据
    const searchData = () => {
      commonSearch(getTeaList(assginPaging(searchForm)))
    }

    // 重置页数查询数据
    const getData = () => {
      resetCurPage()
      searchData()
    }

    // 获取茶叶的类型
    const getTeaTypes = async () => {
      tableLoading.value = true
      try {
        const { code, msg, data } = await getTypeList({ typeCode: "", typeName: "" })
        tableLoading.value = false
        if (isSuccessCode(code)) {
          console.log(data);
          
          teaTypeOptions.value = data.map(d => ({
            label: d.typeName,
            value: d.typeId
          }))
          return
        }

        useElMessageBox({
          type: "warning",
          content: msg
        })
      } catch (e) {
        tableLoading.value = false
        useElMessageBox({
          type: "warning",
          content: e
        })
      }
    }

    // 添加商品图片
    const addPicture = () => {
      handleRadioRow<CommodityListType>((data) => {
        targetTeaId.value = data.teaId
        teaDetailVisible.value = true
      })
    }

    // 创建工具的配置
    const toolsList: ToolsItemType[] = [
      {
        type: "button", content: "新增", attr: {
          onClick: add
        }
      },
      {
        type: "button", content: "编辑", attr: {
          onClick: edit
        }
      },
      {
        type: "button", content: "更多图片", attr: {
          onClick: addPicture
        }
      },
      {
        type: "button", content: buttonFlag, attr: {
          onClick: () => handleEnable<CommodityListType>((data) => enableCommdity({
            teaId: data.teaId,
            enable: searchForm.enable === 1 ? 0 : 1
          }), searchData)
        }
      },
      {
        type: "checkbox",
        optionLabel: checkboxFlag,
        feild: "enable",
        attr: {
          'true-label': 1,
          'false-label': 0,
          onChange: () => searchData()
        },
        vModel: searchForm
      }
    ]
    
    // 搜索条件的配置
    const condition: ConditionItemType<typeof searchForm>[] = [
      {
        type: "select",
        vModel: searchForm,
        feild: "teaType",
        label: "茶叶类型",
        labelWidth:'5rem',
        col: 4,
        attr: {
          placeholder: "茶叶类型",
          onChange: getData
        },
        option: teaTypeOptions
      },
      {
        type: "text",
        vModel: searchForm,
        feild: "teaName",
        label: "茶叶名称",
        labelWidth:'5rem',
        col: 6,
        attr: {
          placeholder: "茶叶名称",
          onClear: searchData,
          onKeydown: (e: KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      },
    ]

    // v2行的配置
    const colmun: TableV2Type["colmunConfig"] = [
      { field: "teaName", type: "radio", title: "茶叶名称",width: 200, treeNode: true },
      {
        type: "slot", field: "cover", title: "封面", width: 120, vNode: ({ row }) => {
          const url = `${baseUrl}${row.cover}`
          return (
            <ElImage previewSrcList={[url]} style={{ width: "100px", height: '100px' }} fit="cover" src={url}></ElImage>
          )
        }
      },
      { field: "typeName", title: "茶叶类别" },
      { field: "price", title: "单价", width: 100 },
      { field: "number", width: 100 ,title: "剩余数量" },
      { field: "creator", width: 100, title: "创建人" },
      { field: "createTime", width: 200 ,title: "创建时间" },
    ]

    // v2 表的配置
    const table: TableV2Type["tableConfig"] = reactive({
      radioConfig: { labelField: 'teaName' },
      data: [],
    })

    const handleSuccess = () => {
      visible.value = false
      searchData()
    }

    onMounted(() => {
      getTeaTypes()
      searchData()
      mountSearch(searchData)
    })

    return () => (
      <section class={`m-padding m-window m-fullBox`}>
        <header class={`m-bottom`}>
          <WorkArea
            tools={toolsList}
            condition={condition}
            onSearch={searchData}
          >
          </WorkArea>
        </header>
        <TableV2
          v-loading={tableLoading.value}
          vexTableV2={{
            tableConfig: table,
            colmunConfig: colmun
          }}
          initPagination={true}
          tableName={tableName}
        />
        <TeaDialog
          ruleForm={ruleForm}
          title={title}
          visible={visible}
          handleSuccess={handleSuccess}
          teaTypeOptions={teaTypeOptions}
        />
        <TeaItemDialog
          visible={teaDetailVisible}
          targetTeaId={targetTeaId}
        />
      </section>
    )
  }
})

export default defineComponent({
  name: "commodityManage",
  setup() {
    return () => (
      <MenuIndex>
        <CommodityManage></CommodityManage>
      </MenuIndex>
    )
  }
})